package at.codebase.web.servlets.admin;

import java.util.ArrayList;
import java.util.List;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EUserDao;
import at.codebase.db.entities.EUser;
import at.codebase.web.templates.MainTemplate;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterException;
import at.codebase.web.util.servlet.SecureServlet;
import at.codebase.web.util.template.Template;
import at.codebase.web.util.template.TemplateEngine;

/**
 * @author Daniel Marth <danielmarth@gmx.at>
 */
public class ManageAdmins extends SecureServlet {

	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ADMIN);
	}

	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		
		if(requestType.equals(RequestType.POST)){
			if(!tokenCorrect(requestInfo)) {
				processRequestNoAccess(requestInfo, level);
				return;
			}
			
			try {
				String action = requestInfo.getParameters().getString("action");
				if(action.equals("addAdmin")){
					long userId = requestInfo.getParameters().getLong("userId");
					EUser user = EUserDao.getUserById(new Long(userId));
					if(user != null && !user.isAdmin() && !user.getId().equals(requestInfo.getUser().getId())){
						user.setAdmin(true);
						EUserDao.saveUser(user);
						Log.logAdmin(requestInfo.getUser().getId(),
								"Admin (userid="
										+ requestInfo.getUser().getId()
										+ ") added an administrator (userid="
										+ userId + ")");
					}
				}else if(action.equals("removeAdmin")){
					long userId = requestInfo.getParameters().getLong("userId");
					EUser user = EUserDao.getUserById(new Long(userId));
					if(user != null && user.isAdmin() && !user.getId().equals(requestInfo.getUser().getId())){
						user.setAdmin(false);
						EUserDao.saveUser(user);
						Log.logAdmin(requestInfo.getUser().getId(),
								"Admin (userid="
										+ requestInfo.getUser().getId()
										+ ") removed an administrator (userid="
										+ userId + ")");
					}
				}
			} catch (ParameterException e) { }
		}		
		
		MainTemplate mainTemplate = new MainTemplate(requestInfo, writer());
		mainTemplate.setTitle("Admin Manage");

		String nextToken = nextToken();
		Template overviewTemplate = TemplateEngine.getTemplate("admin/site_manage.html");
		overviewTemplate.setTemplate("adminMenuBar", TemplateEngine.getTemplate("admin/admin_menu_bar.html"));
		overviewTemplate.setText("randomKey", nextToken);
		
		ArrayList<Template> adminRowTemplates = new ArrayList<Template>();
		List<EUser> admins = EUserDao.getAdmins();
		
		for(EUser admin:admins){
			Template template = TemplateEngine.getTemplate("admin/manage/manage_row.html");
			template.setText("userid", admin.getId().toString());
			template.setText("username", admin.getUsername());
			
			// XSRF protection
			template.setText("randomKey", nextToken);
			
			adminRowTemplates.add(template);
		}
		overviewTemplate.setTemplates("adminList", adminRowTemplates);
		
		mainTemplate.setTemplate("body", overviewTemplate);
		mainTemplate.render(requestInfo.getLocale());
		
		/*
		writer().printInsecure("<html><body>");
		if(requestInfo.getParameters().isExisting("userId")) {
			if(requestInfo.getParameters().isExisting("ref")) {
				try {
					if(requestInfo.getParameters().getString("ref").equals("toggle")) {
						String userIdString = requestInfo.getParameters().getString("userId");
						Long userId = new Long(userIdString);
						EUser user = EUserDao.getUserById(userId);
						writer().printInsecure("User ");
						writer().printSecure(user.getUsername());
						if(user.isActive()) {
							writer().printInsecure(" was activated.");
						} else {
							writer().printInsecure(" was deactivated.");
						}
						writer().printInsecure("<br />");
					}
				} catch (ParameterDoesNotExistException e) {
					writer().printInsecure("<h2>ERROR</h2>");
				}
			}
		}
		writer().printInsecure("<table>");
		for (EUser eUser : EUserDao.getAllUsers()) {
			writer().printInsecure("<tr>");
			writer().printInsecure("<td>");
			writer().printSecure(eUser.getId().toString());
			writer().printInsecure(":</td>");
			writer().printInsecure("<td>");
			writer().printSecure(eUser.getUsername());
			writer().printInsecure("</td>");
			writer().printInsecure("<td>");
			writer().printSecure(String.valueOf(eUser.isActive()));
			writer().printInsecure("</td>");
			writer().printInsecure("<td>");
			writer().printInsecure("<form method=\"POST\" action=\"");
			writer().printInsecure(ServletList.ToggleUserActive);
			writer().printInsecure("\">");
			writer().printInsecure("<input name=\"userId\" type=\"hidden\" value=\"");
			writer().printSecure(eUser.getId().toString());
			if(eUser.isActive()) {
			writer().printInsecure("\"><button type=\"submit\">Deactivate</button>");
			} else {
				writer().printInsecure("\"><button type=\"submit\">Activate</button>");
			}
			writer().printInsecure("</form></td>");
			writer().printInsecure("</tr>");
		}
		writer().printInsecure("</table></body></html>");
		*/
	}

	
	@Override
	protected RequestType requestType() {
		// FIXME
		return RequestType.POST_AND_GET;
	}

}
